//
//  PreviewPhotoViewController.m
//  YCSchool
//
//  Created by yanglinxia on 16/5/3.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "PreviewPhotoViewController.h"
#import "PreviewPhotoCell.h"

@interface PreviewPhotoViewController()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *images;
@property (nonatomic, assign) NSUInteger currentIndex;
@property (nonatomic, copy) PreviewPhotosClickRightBarButtonItemBlock block;
@property (nonatomic, strong) NSString *rightBarButtonItemTitle;
@property (nonatomic, strong) NSString *rightBarButtonItemImageName;
///集合视图
@property (nonatomic, strong) UICollectionView *collectionView;
@end
@implementation PreviewPhotoViewController

- (UICollectionView *)collectionView
{
    if(!_collectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.itemSize = self.view.bounds.size;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [_collectionView registerClass:[PreviewPhotoCell class] forCellWithReuseIdentifier:@"cell"];
    }
    return _collectionView;
}

- (void)setCurrentIndex:(NSUInteger)currentIndex
{
    _currentIndex = currentIndex;
    self.navigationItem.title = [NSString stringWithFormat:@"%lu/%lu",currentIndex + 1,self.images.count];
}

#pragma mark - 生命周期

- (instancetype)initWithImages:(NSMutableArray *)images displayIndex:(NSUInteger)index rightBarButtonItemImageName:(NSString *)imageName clickBlock:(PreviewPhotosClickRightBarButtonItemBlock)block
{
    if(self = [super init])
    {
        _images = images;
        self.currentIndex = index;
        _rightBarButtonItemImageName = ((imageName==nil||[imageName isEqual:@""]) ? @"PreviewPhotoDelete":imageName);;
        _block = block;
    }
    return self;
}

- (instancetype)initWithImages:(NSMutableArray *)images displayIndex:(NSUInteger)index rightBarButtonItemTitle:(NSString *)title clickBlock:(PreviewPhotosClickRightBarButtonItemBlock)block
{
    if(self = [super init])
    {
        _images = images;
        self.currentIndex = index;
        _rightBarButtonItemTitle = ((title==nil||[title isEqual:@""]) ? @"删除":title);
        _block = block;
    }
    return self;
}

// 导航右边设置
- (void)setupNavBarWithTitle:(NSString *)rightButtonTitle
{
    [self.navigationItem hidesBackButton];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"PhotoNavBack"] style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(popViewControllerAnimated:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    // 删除
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:rightButtonTitle forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [rightButton setTitleColor:[UIColor colorWithRed:0.0 green:180/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    [rightButton sizeToFit];
    [rightButton addTarget:self action:@selector(didTouchUpInsideWithUsingBarButtonItem:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
}

// 右边为图片
- (void)setupNavBarWithImageName:(NSString *)rightButtonImageName
{
    [self.navigationItem hidesBackButton];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"PhotoNavBack"] style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(popViewControllerAnimated:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    // 删除
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:rightButtonImageName] forState:UIControlStateNormal];
    [rightButton sizeToFit];
    [rightButton addTarget:self action:@selector(didTouchUpInsideWithUsingBarButtonItem:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
    if(self.rightBarButtonItemTitle)
    {
        [self setupNavBarWithTitle:self.rightBarButtonItemTitle];
    }
    
    if(self.rightBarButtonItemImageName)
    {
        [self setupNavBarWithImageName:self.rightBarButtonItemImageName];
    }
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if(self.images.count > 0)
    {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - 点击删除

- (void)didTouchUpInsideWithUsingBarButtonItem:(UIBarButtonItem *)UsingButton
{
    UICollectionViewCell *cell = [self.collectionView visibleCells].firstObject;
    NSUInteger index = [self.collectionView indexPathForCell:cell].row;
    if(self.block) self.block(self,self.images,index);
}

#pragma mark - 重载
- (void)reloadWithImages:(NSMutableArray *)images displayIndex:(NSUInteger)index
{
    _images = images;
    self.currentIndex = index;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.collectionView reloadData];
        
    } completion:^(BOOL finished) {
        
        if (_images.count == 1)
        {
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            self.title = @"1/1";
        }
        else
        {
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }
        
        
    }];
}

#pragma mark - UICollectionView datasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.images.count;
}

#pragma mark - UICollectionView delegate

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PreviewPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if ([self.images[indexPath.row] isKindOfClass:[UIImage class]])
    {
        UIImage *image = self.images[indexPath.row];
        [cell.previewView zoomImage:image];
    }
    else
    {
        [cell.previewView zoomImageWithURLString:self.images[indexPath.row] placeholderImage:nil];
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return collectionView.bounds.size;
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    CGFloat width = scrollView.frame.size.width;
    NSUInteger index = (point.x / width);
    self.currentIndex = index;
}


@end
